import random
import string

from django.contrib.auth.models import User, Group
from django.shortcuts import render
from rest_framework.response import Response
from rest_framework.viewsets import ModelViewSet, ViewSet
from rest_framework.status import HTTP_404_NOT_FOUND

from celery_tasks.email.tasks import send_mail_task
from users.serializers import CreateUserSerializer
from .models import Classes
from .serializers import ClassesSerializer
# from rest_framework.permissions import IsAuthenticated
from users.utils import MyPermission
# Create your views here.


class ClassesViewSet(ModelViewSet):
    # permission_classes = [IsAuthenticated]
    permission_classes = [MyPermission]
    queryset = Classes.objects.filter(is_delete=False)
    serializer_class = ClassesSerializer


class ClassesStudentViewSet(ViewSet):

    # 获取班级
    # 判断该用户是否属于该班级
    # 属于： 返回提示
    # 不属于：判断该用户是否存在
    #   存在： 添加到该班级中
    #   不存在： 创建用户，并添加到班级中
    #     生成初始密码、添加学生身份、添加至该班级
    #     发送邮箱进行通知 并且发送初始密码给用户

    permission_classes = [MyPermission]
    serializer_class = CreateUserSerializer

    def add_member(self, request, pk):
        try:
            classes = Classes.objects.get(id=pk)
        except Classes.DoesNotExist:
            return Response(status=HTTP_404_NOT_FOUND)

        username = request.data['username']
        member = classes.member.filter(username=username)

        if member:
            return Response({'msg': '该成员已加入该班级'})

        user = User.objects.filter(username=username)
        if user:
            classes.member.add(user[0])
            return Response(CreateUserSerializer(user[0]).data)
        else:
            userSerializer = CreateUserSerializer(data=request.data)
            userSerializer.is_valid(raise_exception=True)

            email = request.data['email']
            first_name = request.data['first_name']
            user = User(username=username, email=email, first_name=first_name)

            source = string.ascii_letters + string.digits
            password = ''.join(random.sample(source, 6))
            user.set_password(password)
            user.save()

            group = Group.objects.get(id=2)
            group.user_set.add(user)

            classes.member.add(user)

            # 使用celery进行邮箱发送
            send_mail_task(email, user.username, password, classes.name)
            return Response(userSerializer.data)




